/*
 * Text.cpp
 *
 *  Created on: Sep 4, 2011
 *      Author: Patrick
 */

#include "Text.h"

int getNextPowerOfTwo(int x) {
	double logBase2 = log(x) / log(2);
	return round(pow(2, ceil(logBase2)));
}

MCTextObject MCTextCreate(char* text, TTF_Font* font, float r, float g, float b) {

	MCTextObject t;
	SDL_Surface *initial;
	SDL_Surface *intermediary;
	SDL_Color color = { b * 255, g * 255, r * 255 };

	t.text = text;
	t.font = font;
	t.color = color;

	glEnable(GL_TEXTURE_2D);

	// Use SDL_TTF to render our text
	initial = TTF_RenderText_Blended(font, text, color);

	// Convert the rendered text to a known format
	t.w = getNextPowerOfTwo(initial->w);
	t.h = getNextPowerOfTwo(initial->h);
	intermediary = SDL_CreateRGBSurface(0, t.w, t.h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
	SDL_BlitSurface(initial, 0, intermediary, 0);

	glGenTextures(1, &t.texture);
	glBindTexture(GL_TEXTURE_2D, t.texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, t.w, t.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, intermediary->pixels);

	SDL_FreeSurface(initial);
	SDL_FreeSurface(intermediary);

	return t;

}

void MCTextRender(MCTextObject t, int x, int y) {

	// Defaults to top left
	glBindTexture(GL_TEXTURE_2D, t.texture);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
	glBegin(GL_QUADS);
	glTexCoord2d(0, 0);
	glVertex2f(x, y);
	glTexCoord2d(1, 0);
	glVertex2f(x + t.w, y);
	glTexCoord2d(1, 1);
	glVertex2f(x + t.w, y + t.h);
	glTexCoord2d(0, 1);
	glVertex2f(x, y + t.h);
	glEnd();
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

}

void MCTextDestroy(MCTextObject t) {

	glDeleteTextures(1, &t.texture);

}
